//
//  searchContactsVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/6/14.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "searchContactsVC.h"
#import "searchContactsFirView.h"
#import "searchContactsCell.h"
#import "goveDetailVC.h"
#import "SearchContacts.h"
#import "thirdPersonVC.h"
#import "topView.h"
#import "mySearchBar.h"
#import "addFriendVC.h"
#import "FriendViewController.h"
#import "friendListVC.h"
#import "searchNewFriendVC.h"

@interface searchContactsVC ()<UITextFieldDelegate,UITableViewDelegate>{
    NSInteger page;
    NSMutableDictionary * dictData;
}
// 数据源
@property (strong, nonatomic) NSDictionary * dataDict;
@property (strong, nonatomic) NSMutableArray * dataArr;
@property (strong, nonatomic) topView * topview;
@property (strong, nonatomic) mySearchBar * search;
@end

static NSString * searchContactscell = @"searchContactsCell";
@implementation searchContactsVC


#pragma mark - 初始化
-(topView *)topview{
    if (!_topview) {
        _topview = [[[NSBundle mainBundle]loadNibNamed:@"topView" owner:self options:nil]lastObject];
    }
    return _topview;
}
-(NSDictionary *)dataDict{
    if (!_dataDict) {
        _dataDict = [NSDictionary dictionary];
    }
    return _dataDict;
}

-(NSMutableArray *)commentArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"找人脉背景"] forBarMetrics:UIBarMetricsDefault];
    //找出导航栏的下边的黑线
    UIImageView *navBarHairlineImageView = [NaviBarLine findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    

    dictData = [NSMutableDictionary dictionary];
    self.tabBarController.tabBar.hidden = YES;
    [self sendRequest];
    
//        [self showRoundProgressWithTitle:@"加载中..."];
    [self showSingleIconBubble:@"我来来事事这个错误控件到底有多长"];
    self.search = [mySearchBar searchBar];
    _search.delegate = self;
    self.navigationItem.titleView = _search;
    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"searchContactsCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:searchContactscell];
    
    page = 1;
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;

    
    //设置头视图
    searchContactsFirView * headView = [[searchContactsFirView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 310)];
    
    self.topview.height = 130;
    self.topview.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:177.0/255.0 blue:241.0/255.0 alpha:1];
    [headView addSubview:self.topview];
    
    headView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headView;
    
    [self.topview.myFriend addTarget:self action:@selector(friend) forControlEvents:UIControlEventTouchUpInside];
    [self.topview.addFriend addTarget:self action:@selector(addfriend) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    UIImage *images = [UIImage imageNamed:@"mj_footer"];
    NSArray *refreshingImages = @[images];
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多内容了" forState:MJRefreshStateRefreshing];
    footer.stateLabel.font = [UIFont systemFontOfSize:12.0f];
    footer.stateLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0f];
    
    [footer setAutomaticallyRefresh:NO];
    
    self.tableView.mj_footer = footer;
    
    //监听通知
    [self setUpListenEvent];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)friend{

    if (!allConstMemberid) {
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        
    }else{
    
    friendListVC * friendList = [[friendListVC alloc]init];
    [self.navigationController pushViewController:friendList animated:YES];
        
    }
}
-(void)addfriend{
//    [SVProgressHUD showErrorWithStatus:@"功能未开放"];
    addFriendVC * addFriend = [[addFriendVC alloc]init];
    [self.navigationController pushViewController:addFriend animated:YES];
}
-(void)loadMoreData{
    
    page++;
    
    [self sendRequest];
    
}
-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
    [self hideBubble];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    searchContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:searchContactscell forIndexPath:indexPath];
    
    NSDictionary * dict = self.dataArr[indexPath.row];
    
    cell.lineview.hidden = YES;
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    [cell.headImg.layer setCornerRadius:(cell.headImg.frame.size.height/2)];
    [cell.headImg.layer setMasksToBounds:YES];
    [cell.headImg setContentMode:UIViewContentModeScaleAspectFill];
    [cell.headImg setClipsToBounds:YES];
    cell.headImg.layer.shadowColor = [UIColor whiteColor].CGColor;
    cell.headImg.layer.shadowOffset = CGSizeMake(4, 4);
    cell.headImg.layer.shadowOpacity = 0.5;
    cell.headImg.layer.shadowRadius = 2.0;
    
    if ([dict[@"userName"] isEqualToString:@""] || [dict[@"userName"] isEqualToString:@"null"]) {
        cell.nameLabel.text = dict[@"account"];
    }else{
        cell.nameLabel.text = dict[@"userName"];
    }
    

    CGSize size = [cell.nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];

    if (size.width<190) {
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, size.width, cell.nameLabel.height)];
    }else{
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, 168, cell.nameLabel.height)];
    }

    cell.lineView.x = cell.nameLabel.x + cell.nameLabel.width + 2;
    
    
    if ([dict[@"positionName"] isEqualToString:@""] || [dict[@"positionName"] isEqualToString:@"null"]) {
        cell.posName.text = @"";
    }else{
        cell.posName.text = dict[@"positionName"];
    }
    CGSize posSize = [cell.posName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (posSize.width <= 60) {
        cell.posName.width = posSize.width;
    }else{
        cell.posName.width = 60;
    }
    
    cell.posName.x = cell.lineView.x + 2;
    cell.vImg.x = cell.posName.x + cell.posName.width;
    
    if (cell.vImg.x > 185) {
        cell.vImg.x = 184;
    }
    
    cell.lineview.hidden = YES;
    //上级
    cell.detailLabel.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
    //会员图标
    cell.vImg.image = [UsedTool setVipimage:dict[@"vipLevel"]];
//    if ([dict[@"authState"]integerValue] == 0) {
//        cell.vImg.image = [UIImage imageNamed:@"weirenzheng"];
//    }else{
//        cell.vImg.image = [UIImage imageNamed:@"yirenzheng"];
//    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 80;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.width, 30)];
    view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];
    UIImageView * img = [[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 60, 15)];
    img.image = [UIImage imageNamed:@"推荐人脉"];
    [view addSubview:img];
        
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    if (allConstMemberid) {
        NSDictionary * dict = _dataArr[indexPath.row];
        
        NSString * str = [USER_DEFAULTS objectForKey:@"userid"];
        NSInteger userid = [str integerValue];
        
        NSString * str1 = dict[@"userId"];
         NSInteger userId = [str1 integerValue];
        
        if (userid != userId) {
            
            if ([dict[@"type"] isEqualToString:@"政府"]) {
                goveDetailVC * prVC = [[goveDetailVC alloc]init];
                prVC.userType = dict[@"userType"];
                prVC.userId = dict[@"userId"];
                [self.navigationController pushViewController:prVC animated:YES];
                
            }else{
                
                thirdPersonVC * prVC = [[thirdPersonVC alloc]init];
                prVC.userType = dict[@"userType"];
                prVC.userId = dict[@"userId"];
                [self.navigationController pushViewController:prVC animated:YES];
            }

        }else{
        
            NSLog(@"点击了自己");
        
        }
        
        
    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    

}

-(void)sendRequest{
    
    // 请求数据
//    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dictData setValue:@(page) forKey:@"page"];
//    dic[@"page"] = @(page);
    
    NSString *str = @"PeopleTuijian_app_people.im";

    [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        self.dataDict = dicInfo[@"data"];

        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            if (page == 1) {
                
                _dataArr = nil;
                _dataArr = self.dataDict[@"record"];
 
                
            }else{
                
                NSArray *arr = self.dataDict[@"record"];
                NSMutableArray * mtArr = [NSMutableArray array];
                for (NSDictionary * dict in _dataArr) {
                    [mtArr addObject:dict];
                }
                for (NSDictionary * dict in arr) {
                    [mtArr addObject:dict];
                }
                _dataArr = nil;
                _dataArr = mtArr;
      
            }
            
            [self.tableView.mj_footer endRefreshing];
            
        }else{

            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];

//        [self hideBubble];
        
    } failure:^(NSError *error) {


       [self showSingleIconBubble:@"网络连接错误"];
        
    }];

}
#pragma mark - 监听通知
-(void)setUpListenEvent{
    
    //分类通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clickCategoryChange:) name:@"clickCategory" object:nil];
}

-(void)clickCategoryChange:(NSNotification *)notification{
    NSString * cityName = notification.userInfo[@"category"];

    
    if (([[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 3 || [[USER_DEFAULTS objectForKey:@"usertype"] integerValue] == 2) && [cityName isEqualToString:@"同行"]){
        
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"只有个人用户才能使用此功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];

        
        
    }else{
        
        
        if (![USER_DEFAULTS objectForKey:@"address"] && ([cityName isEqualToString:@"同城"] || [cityName isEqualToString:@"找老乡"])) {

            [self showSingleIconBubble:@"尚未添加地址"];
            
        }else{
        
            //取消显示后退键文字
            UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
            self.navigationItem.backBarButtonItem = barButtonItem;
            
            UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
            
            
            SearchContacts *SearchContactvc = [sb instantiateViewControllerWithIdentifier:@"searchContacts"];
            SearchContactvc.titleStr = cityName;
            
            if ([cityName isEqualToString:@"同行"]) {
                
                if (allConstMemberid) {
                    
                    SearchContactvc.industry = [USER_DEFAULTS objectForKey:@"industry"];
                    [self.navigationController pushViewController:SearchContactvc animated:YES];
                    
                }else{
                
                    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
                    [alert show];
                    
                }
                
            }else{
            
            //跳转事件
            [self.navigationController pushViewController:SearchContactvc animated:YES];
                
            }
        }
        
    }
    

    NSLog(@"%@",cityName);
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length >= 1) {
        
        searchNewFriendVC * searchNewFriend = [[searchNewFriendVC alloc]init];
        searchNewFriend.mhName = textField.text;
        
        [self.navigationController pushViewController:searchNewFriend animated:YES];
        
        [self.view endEditing:YES];
        self.search.text = nil;
        [self.search resignFirstResponder];
        NSLog(@"完成编辑");
        return YES;
        
    }else{

        [self showSingleIconBubble:@"关键词不能为空"];
        return NO;
    }

}
#pragma mark - alertview
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [self presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}
@end
